<?php
namespace plugins\logistics\controller;
use cmf\controller\PluginAdminBaseController;
use think\Db;
use think\Request;
use plugins\store\Common;
/**
 *
 */
class AdminIndexController extends PluginAdminBaseController
{
    /**
     * 初始化
     */
    private  $pageNum = "20";
    protected  $LOGISTICS;
    private  $com = '';
    public function _initialize()
    {
        $this->com = new Common;
        $dir =  dirname(__FILE__);
        $file=scandir($dir);
        unset($file[0],$file[1]);//因为这样获取到的数组前两位是. 和..,所以删去
        foreach($file as $key =>$value)
        {
            $logistics ='';
            if(substr($value,0,9)=== 'Logistics')
            {
                $logistics = $value;
                break;//终止循环
            }
        }

        if(!empty($logistics))
        {
            $logistics = str_replace(strrchr($logistics, "."),"",$logistics);
            $res = '\\plugins\logistics\controller\\'.$logistics;
            $this->LOGISTICS = new $res();
        }else{ echo 'false'; }
    }
    /**
     * 首页物流公司管理
     */
    public function index()
    {
        $param = $this->request->param();
        $sear['pagesize'] = isset( $param['pagesize'] ) ? $param [ 'pagesize' ] : $this->pageNum;

        $data = db('logistics')->paginates($sear['pagesize'] , false ,['query'=>$sear]);
        $data->appends($sear);
        $this->assign('page',$data->render());//单独提取分页
        $this->assign('data',$data);
        return $this->fetch();
    }
    /**
     * 添加
     */
    public function addPage()
    {
        $data = $this->request->post();
        if($this->request->isPost())
        {
            $res = db('logistics')->insert($data);
            if($res ){
                return api_json_echo(true,'添加成功','',200);
            }else{
                return api_json_echo(false,'添加失败','',100);
            }
        }

        return $this->fetch('admin_index/addPage');
    }
    /**
     * 编辑
     */
    public function editPage()
    {
        $param = $this->request->param();
        $data = db('logistics')->where('id',$param['id'])->find();
        if($this->request->isPost())
        {
            $post = $this->request->post();
            $data = db('logistics')->update($post);
            if($data ){
                return api_json_echo(true,'添加成功','',200);
            }else{
                return api_json_echo(false,'添加失败','',100);
            }

        }

        $this->assign('data',$data);
        return $this->fetch('admin_index/editPage');
    }
    /**
     * 删除
     */
    public function delete()
    {
        $param = $this->request->post();
        $data = db('logistics')->where('id','in',$param['id'])->delete();
        return api_json_echo(true,'删除','',200);
    }
     /**
     * 电子面单
     * @param   $ShipperCode 快递公司代码
     * @param   $OrderCode 订单编号
     * @param   $GoodsName 商品名称
     * @param  array $sender 寄件人  ["Name"=>"寄件人","Mobile"=>"电话","ProvinceName"=>"省","CityName"=>"市","ExpAreaName"=>"区","Address"=>"详细地址"]
     * @param  array $receiver 提交的数据收件人  ["Name"=>"收件人","Mobile"=>"电话","ProvinceName"=>"省","CityName"=>"市","ExpAreaName"=>"区","Address"=>"详细地址"]
     * @return
     */
    public function placeOrder($ShipperCode='',$OrderCode='',$sender='',$receiver='',$GoodsName="其他"){
        $api = $this->LOGISTICS;
        if(is_callable(array($api, 'placeOrder'))){
            $res = $this->LOGISTICS->placeOrder($ShipperCode,$OrderCode,$sender,$receiver,$GoodsName);
        } else {
            $res = [];
        }
        return api_json_echo(true,'结果',$res,200);
    }
     /**
     * 打印
     * @param  array $OrderCode 订单编号  ['012657700387','012657700387']
     * @return url响应返回的html
     */
    public function orderPrint($OrderCode=[]){
        //店铺id
        $allow = $this->com->getAllowAccess();
        if($allow == 'true') $allow = 'admin';
        $where['store_id'] =['=', $allow ];
        if ( !empty(input('start_time')) ) {
            $where['delivery_time']  = ['>=',strtotime( input('start_time'))];
        }
        if ( !empty(input('end_time')) ) {
            $where['delivery_time']  = ['<=',strtotime( input('end_time') )];
        }
        if( !empty(input('start_time')) && !empty(input('end_time'))){
            $where['delivery_time']  = [['>=',strtotime( input('start_time'))],['<=',strtotime( input('end_time') )],'AND'];
        }
        if (!empty(input('status'))) {
            $where['status']  = ['=',input('status')];
        }
        if (!empty(input('code'))) {
            $where['code']  = ['=',input('code')];
        }
        if( input('type') !== '1'){
            return  '只有线上电子面单可打印' ;
        }else{
            $where['type']  = ['=',input('type')];
        }
        $arr = db('logistics_order')->where($where)->field('order_num,logistics_code') ->select();

        foreach( $arr as $key => $value ) {
            $data[] = $value['order_num'];
        }
        $OrderCode = isset($data) ? $data : $OrderCode;

        $api = $this->LOGISTICS;
        if(is_callable(array($api, 'order_print'))){
            $res = $this->LOGISTICS->order_print($OrderCode);
            $this->exmodel( $arr );
        } else {
            $res = [];
        }
        return api_json_echo(true,'结果',$res,200);
    }
    /**
     * 电子打印订单编号-物流单号
     */
    public function exmodel($order_num=[])
    {
        if(empty($order_num)) return false;
        require_once 'classes/phpexcel/PHPExcel.php';
        //实例化
        $objPHPExcel = new \PHPExcel();
        /*右键属性所显示的信息*/
        $objPHPExcel->getProperties()->setCreator("cy")  //作者
        ->setLastModifiedBy("cy")  //最后一次保存者
        ->setTitle('数据EXCEL导出')  //标题
        ->setSubject('数据EXCEL导出') //主题
        ->setDescription('导出数据')  //描述
        ->setKeywords("excel")   //标记
        ->setCategory("result file");  //类别
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);
        // 设置表格第一行显示内容
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', '订单编号')
            ->setCellValue('B1', '物流单号')
            //设置第一行为红色字体
            ->getStyle('I1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_RED);
        $objPHPExcel->getActiveSheet()->setTitle('电子面单批量打印表');
        $key = 1;
        /*以下就是对处理Excel里的数据，横着取数据*/
        foreach($order_num as $v){
            //设置循环从第二行开始
            $key++;
            $objPHPExcel->getActiveSheet()
                //Excel的第A列，name是你查出数组的键值字段，下面以此类推
                ->setCellValue('A'.$key, $v['order_num'])
                ->setCellValue('B'.$key, $v['logistics_code']);
        }
        //设置当前的表格

        $name = '电子面单批量打印表';
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();  //清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel'); //文件类型
        header('Content-Disposition: attachment;filename="'.$name.'.xls"'); //文件名
        header('Cache-Control: max-age=0');
        header('Content-Type: text/html; charset=utf-8'); //编码
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel 2003
        $objWriter->save('php://output');
        exit;
    }
}